package org.pjlib.net;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.StringUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;
import com.lzy.okgo.model.HttpMethod;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;

import org.json.JSONException;
import org.json.JSONObject;
import org.pjlib.Logs;

import java.net.Proxy;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * Created by ws on 2019/02/21.
 * 网络加载帮助类，一定要在Application onCreate()调用 HttpUtils.getInstance().init(this);或者自定义继承BaseApp
 */
public class HttpUtils {
    private static HttpUtils httpUtils;
    private static OkHttpClient okHttpClient;
    private static String baseUrl="https://www.tuyazb.com/";

    public static HttpUtils getInstance() {
        if (httpUtils == null) {
            httpUtils = new HttpUtils();
        }
        return httpUtils;
    }

    public static void setBaseUrl(String baseUrl) {
        HttpUtils.baseUrl = baseUrl;
    }

    public static String getBaseUrl() {
        return baseUrl;
    }

    public void init(Application app) {
        OkGo.getInstance().init(app)                           //必须调用初始化
                .setOkHttpClient(getOkHttpClient())               //建议设置OkHttpClient，不设置会使用默认的
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式，默认不使用缓存，可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间，默认永不过期，可以不传
                .setRetryCount(3);
    }

    public static void setOkHttpClient(OkHttpClient client) {
        okHttpClient = client;
        OkGo.getInstance().setOkHttpClient(okHttpClient);
    }

    public static OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {

            //log相关
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkHttp");
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别，决定了log显示的详细程度
            loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别，决定了log在控制台显示的颜色
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);    //全局的读取超时时间
            builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
            builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
            // .addInterceptor(loggingInterceptor);  //启用log注释关了就行
            builder.proxy(Proxy.NO_PROXY);
            okHttpClient = builder.build();
        }
        return okHttpClient;
    }

    public static void cancelTag(Object tag) {
        OkGo.cancelTag(getOkHttpClient(), tag);
    }

    public static void cacaelAll() {
        OkGo.cancelAll(getOkHttpClient());
    }

    public static void get(RequestCall call, JsonCallBack callBack) {
        get(call, callBack, true);
    }

    public static void post(RequestCall call, JsonCallBack callBack) {
        post(call, callBack, true);
    }

    public static PostRequest post(RequestCall call, JsonCallBack callBack, boolean isExecute) {
        Request r = request(call, callBack, isExecute, HttpMethod.POST);
        if (r instanceof PostRequest) {
            return (PostRequest) r;
        } else {
            return null;
        }
    }

    public static GetRequest get(RequestCall call, JsonCallBack callBack, boolean isExecute) {
        Request r = request(call, callBack, isExecute, HttpMethod.GET);
        if (r instanceof GetRequest) {
            return (GetRequest) r;
        } else {
            return null;
        }
    }



    public static Request request(RequestCall call, JsonCallBack callBack, boolean isExecute, HttpMethod method) {
        Request request = null;
        String url=call.getUrl();
        if(!url.startsWith("http://")){
            url=String.format("%s/%s",  HttpUtils.baseUrl,url);
        }
        if (method == HttpMethod.GET) {
            request = OkGo.<String>get(url);
        } else if (method == HttpMethod.POST) {
            request = OkGo.<String>post(url);
        }
        if (ObjectUtils.isEmpty(callBack.getNetTag())){
            request.tag(callBack);
        }else {
            request.tag(callBack.getNetTag());
        }
        request.cacheMode(CacheMode.NO_CACHE);
        if (call.getHeaders() != null) {
            request.headers(call.getHeaders());
        }
        if (call.getParams() != null) {
            request.params(call.getParams());
        }
        if (isExecute) {
            request.execute(getCallBack(call, callBack));
        }
        return request;
    }

    public static Callback<String> getCallBack(final RequestCall call, final JsonCallBack callBack) {
        return new StringCallback() {

            @Override
            public void onStart(Request<String, ? extends Request> request) {
                callBack.onBeforeRequest(call);
            }

            @Override
            public void onSuccess(Response<String> response) {
                onSuccess(response.body());
            }

            private void onSuccess(String json) {
                try {
                    JSONObject jsonO = new JSONObject(json);
                    call.setJson(jsonO);
                    callBack.onResponseSuccess(call);
                } catch (JSONException e) {
                    callBack.onResponseError(e, call);
                    if(Logs.debug){
                        showLog(call, callBack, "解析出错：");
                        Logs.w("HttpUtils","data:"+json);
                    }
                    return;
                }
                if(Logs.debug) {
                    showLog(call, callBack, "请求成功：");
                }
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                onSuccess(response.body());
            }

            @Override
            public void onError(Response<String> response) {
                callBack.onResponseError(response.getException(), call);
                showLog(call, callBack, "请求出错：" + response.getException());
            }

            @Override
            public void onFinish() {
                callBack.onFinishRequest(call);
            }

        };
    }

    private static void showLog(RequestCall call, JsonCallBack callBack, String strs) {
        if (call == null || callBack == null || !Logs.debug) {
            return;
        }
        StringBuilder sb = new StringBuilder(strs);
        sb.append("\n");
        sb.append(callBack.getNetTag().getClass().getSimpleName());
        sb.append("\n");
        sb.append(HttpUtils.baseUrl);
        sb.append("/");
        sb.append(call.getUrl());
        if (null != call.getParams()) {
            sb.append("?");
            sb.append(call.getParams().toString());
        }
        if(!strs.contains("出错")) {
            sb.append("\n请求结果：\n---------------------------------------------------\n");
            if (!ObjectUtils.isEmpty(call.getJson())) {
                sb.append(call.getJson().toString());
            }
            sb.append("\n---------------------------------------------------");
        }
        String log=sb.toString().replace("[","").replace("]","");
        if(strs.contains("出错")){
            Logs.w("HttpUtils", log);
        }else
        Logs.i("HttpUtils",log);

    }
}
